import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import '../../../core/models/hot_item.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../../community/pages/community_detail_page.dart';
import '../../ai_companion/pages/mystical_wisdom_sanctuary.dart';

/// 主页内容
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    // 初始化热门项目数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<HotItemProvider>().initialize();
    });
  }

  /// Handle instrument button tap
  void _handleInstrumentTap(String instrument) {
    // 跳转到教学页面，并选中对应的tab
    Navigator.pushNamed(
      context,
      '/learning-hub',
      arguments: instrument.toLowerCase(),
    );
  }

  /// Handle smart assistant button tap
  void _handleSmartAssistantTap() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const MysticalWisdomSanctuary(),
      ),
    );
  }

  /// Handle hot item tap
  void _handleHotItemTap(HotItem item) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CommunityDetailPage(item: item)),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // Required for AutomaticKeepAliveClientMixin
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/one-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: SingleChildScrollView(
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 乐器按钮区域
              _buildInstrumentButtons(),

              // 智能助手按钮
              _buildSmartAssistantButton(),

              // 热门标题
              _buildHotTitle(),

              // 热门列表
              _buildHotGrid(),

              // 添加底部间距，确保内容不被底部导航栏遮挡
              SizedBox(height: 140.h),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建乐器按钮区域
  Widget _buildInstrumentButtons() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 6.w),
      child: AspectRatio(
        aspectRatio: 363 / 299,
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home-button.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Stack(
            children: [
              // Guitar按钮 - 左侧
              Positioned(
                left: 20.w,
                top: 110.h,
                child: _buildInstrumentButton(
                  'assets/images/guitar-button.png',
                  'Guitar',
                  106 / 101,
                ),
              ),

              // Piano按钮 - 中间，稍微高一些
              Positioned(
                left: 120.w,
                top: 95.h,
                child: _buildInstrumentButton(
                  'assets/images/piano-button.png',
                  'Piano',
                  106 / 101,
                ),
              ),

              // Drum按钮 - 右侧，稍微低一些
              Positioned(
                right: 40.w,
                top: 80.h,
                child: _buildInstrumentButton(
                  'assets/images/drum-button.png',
                  'Drum',
                  106 / 101,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建单个乐器按钮
  Widget _buildInstrumentButton(
    String imagePath,
    String instrument,
    double aspectRatio,
  ) {
    return GestureDetector(
      onTap: () => _handleInstrumentTap(instrument),
      child: Container(
        width: 106.w,
        height: 101.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(imagePath),
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }

  /// 构建智能助手按钮
  Widget _buildSmartAssistantButton() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 0.h, bottom: 20.h),
      child: GestureDetector(
        onTap: _handleSmartAssistantTap,
        child: Container(
          width: double.infinity,
          height: 79.h,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/ai-assistant.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建热门标题
  Widget _buildHotTitle() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      alignment: Alignment.centerLeft,
      child: Text(
        'Popular',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20.sp,
          fontFamily: 'Porter Sans Block',
          shadows: [
            Shadow(
              offset: const Offset(1, 1),
              blurRadius: 3,
              color: Colors.black.withValues(alpha: 0.5),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建热门网格
  Widget _buildHotGrid() {
    return Consumer<HotItemProvider>(
      builder: (context, hotItemProvider, child) {
        final items = hotItemProvider.recommendedItems;

        if (hotItemProvider.isLoading) {
          return Container(
            height: 200.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            child: const Center(child: CircularProgressIndicator()),
          );
        }

        if (items.isEmpty) {
          return Container(
            height: 200.h,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            child: Center(
              child: Text(
                'No hot content available',
                style: TextStyle(color: Colors.white, fontSize: 16.sp),
              ),
            ),
          );
        }

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: GridView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 172 / 193,
              crossAxisSpacing: 0.w,
              mainAxisSpacing: 0.h,
            ),
            itemCount: items.length,
            itemBuilder: (context, index) {
              return _buildHotItem(items[index]);
            },
          ),
        );
      },
    );
  }

  /// 构建单个热门项目
  Widget _buildHotItem(HotItem item) {
    return GestureDetector(
      onTap: () => _handleHotItemTap(item),
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/card-bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Padding(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 20.h,
            bottom: 30.h,
          ),
          child: Stack(
            children: [
              // 内容图片
              Container(
                width: double.infinity,
                height: double.infinity,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child: _buildItemImage(item),
                ),
              ),

              if (item.isVideo)
                Center(
                  child: Icon(
                    MyIcons.iconPlayFill,
                    color: Colors.white,
                    size: 22.sp,
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建项目图片
  Widget _buildItemImage(HotItem item) {
    final imageUrl = item.displayImageUrl;

    // 判断是否为本地assets图片
    if (imageUrl.startsWith('assets/')) {
      return Image.asset(
        imageUrl,
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(
              Icons.image_not_supported,
              color: Colors.grey[600],
              size: 40.sp,
            ),
          );
        },
      );
    }

    // 判断是否为本地文件路径
    if (imageUrl.startsWith('/') || imageUrl.startsWith('file://')) {
      return Image.file(
        File(imageUrl.replaceFirst('file://', '')),
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(
              Icons.image_not_supported,
              color: Colors.grey[600],
              size: 40.sp,
            ),
          );
        },
      );
    }

    // 网络图片
    return Image.network(
      imageUrl,
      fit: BoxFit.cover,
      width: double.infinity,
      height: double.infinity,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return Container(
          color: Colors.grey[200],
          child: Center(
            child: CircularProgressIndicator(
              value:
                  loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                      : null,
            ),
          ),
        );
      },
      errorBuilder: (context, error, stackTrace) {
        return Container(
          color: Colors.grey[300],
          child: Icon(
            Icons.image_not_supported,
            color: Colors.grey[600],
            size: 40.sp,
          ),
        );
      },
    );
  }
}
